import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

export function EditRoleDialog({ role, open, onOpenChange, onSave }) {
  const [formData, setFormData] = useState({
    id: "",
    name: "",
    description: "",
    permissions: [],
  });

  // 当角色数据变化时更新表单
  useEffect(() => {
    if (role) {
      setFormData({
        id: role.id,
        name: role.name,
        description: role.description,
        permissions: role.permissions || [],
      });
    }
  }, [role]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSave(formData);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className='sm:max-w-[425px]'>
        <DialogHeader>
          <DialogTitle>编辑角色</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className='grid gap-4 py-4'>
            <div className='grid grid-cols-4 items-center gap-4'>
              <Label htmlFor='name' className='text-right'>
                角色名称
              </Label>
              <Input
                id='name'
                name='name'
                value={formData.name}
                onChange={handleChange}
                className='col-span-3'
                disabled={formData.name === "管理员"}
              />
            </div>
            <div className='grid grid-cols-4 items-start gap-4'>
              <Label htmlFor='description' className='text-right'>
                描述
              </Label>
              <Textarea
                id='description'
                name='description'
                value={formData.description}
                onChange={handleChange}
                className='col-span-3'
              />
            </div>
            {/* 如果需要编辑权限，可以在这里添加权限选择组件 */}
          </div>
          <DialogFooter>
            <Button
              type='button'
              variant='outline'
              onClick={() => onOpenChange(false)}
            >
              取消
            </Button>
            <Button type='submit'>保存修改</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
